import React, { useEffect, useMemo, useState } from 'react';
import { Dropdown, Space, Menu, Modal, message } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { useMenuActions, useMenuData, useMenuSelected, useSkipDirect } from '../../store/menuStore';
import useUserStore, { useToLogin, useUserActions, useUserInfo } from '../../store/userStore';
import { isExternal, sendMessageToParent } from '@/utils/index'
import { useLocation } from 'react-router-dom';
import { singleLogout } from '@/api/login';

const menuFilter = (arr) => {
  return arr.map((item) => {
    let data = { label: item.name, key: item.id }
    if (item.children) {
      data.children = menuFilter(item.children)
    }
    return data
  })
}

const findMenuItemByUrl = (arr, code) => {
  let result;
  arr.find((d) => {
    let url = (d.url || d.path || '').split('?')[0]
    if (isExternal(url)) {
      url = new URL(url).pathname
    }
    if (url && code.includes(url)) {
      result = d
      return true
    } else if (d.children) {
      result = findMenuItemByUrl(d.children, code)
      return Boolean(result)
    }
  })
  return result
}

const Header = ({ style: headerStyle }) => {
  const [latesTime, setLatesTime] = useState(dayjs().format('YYYY-MM-DD HH:mm:ss'));
  const menuData = useMenuData()
  // const menuSelected = useMenuSelected()
  const skipDirect = useSkipDirect()
  const { findByIdMenu, toSSOLogout } = useMenuActions()
  const { logout } = useUserActions()
  const toLogin = useToLogin()
  const { userInfo } = useUserStore()
  const [menuSelected, setMenuSelected] = useState()

  const routerLocation = useLocation()

  const modelMenus = useMemo(() => {
    return menuFilter(menuData)
  }, [menuData])

  useEffect(() => {
    // 设置一个定时器
    const timerId = setInterval(() => {
      setLatesTime(dayjs().format('YYYY-MM-DD HH:mm:ss'));
    }, 1000);
    // 清除定时器
    return () => clearInterval(timerId);
  }, [])

  useEffect(() => {
    setMenuSelected(findMenuItemByUrl(menuData, routerLocation.pathname))

  }, [routerLocation, menuData])

  const onClick = (e) => {
    let activeMenu = findByIdMenu(e.key)
    if (activeMenu) {
      skipDirect(activeMenu)
    }
  };

  const logoutConfirm = () => {
    Modal.confirm({
      title: '提示',
      content: '确定注销并退出系统吗？',
      onOk: () => {
        if (window.parent !== window) {
          // console.log('当前页面在 iframe 中');
          sendMessageToParent({ type: 'logout' })
        } else {
          singleLogout().then((res) => {
            if (res.errorCode === '0') {
              logout()
              toSSOLogout()
            } else {
              message.error(res.errorMsg)
            }
          })
        }
        // window.location.href = `http://${constantObjSSO.SSO_HOST}/esc-sso/logout`
        // this.$router.push({ name: 'login' })
      },
      onCancel() { }
    })
  }
  const userEvent = ({ key }) => {
    switch (key) {
      case '1':
        break;
      case '2':
        logoutConfirm()
        break;
      default:
        break;
    }
  }

  return (
    <header className="layout-header" style={headerStyle}>
      {/* <div className="pull-left cursor-pointer">
        <div className="logo-p">
          <span>{'应用集成管理'}</span>
        </div>
      </div> */}
      <div className="layout-top-nav">
        <Menu
          onClick={onClick}
          selectedKeys={[menuSelected?.id]}
          mode="horizontal"
          items={modelMenus}
        />
      </div>
      <div className="pull-right user-setting">
        <span>{latesTime}</span>
        <span className="sep">|</span>
        {/* {userInfo.userName} */}
        <Dropdown
          menu={{
            items: [
              // {
              //   key: '1',
              //   label: '修改密码',
              // },
              {
                key: '2',
                danger: true,
                label: '退出系统',
              },
            ],
            onClick: userEvent
          }}
          trigger={['click']}
        >
          <a onClick={(e) => e.preventDefault()}>
            <Space>
              {userInfo.userName}
              <DownOutlined />
            </Space>
          </a>
        </Dropdown>
      </div>
    </header>
  );
};
export default Header;
